package learnjava.concur.chapter4;

/**
 * 交替输出：三个线程交替输出a,b,c五次
 */

public class P081 {

    static Object lock = new Object();
    static int flag = 0;

    public static void main(String[] args) {

        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                synchronized (lock){
                    while (flag%3!=0) { //可能虚假唤醒
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("a");
                    flag++;
                    lock.notifyAll();
                }
            }
        }).start();

        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                synchronized (lock){
                    while (flag%3!=1) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("b");
                    flag++;
                    lock.notifyAll();
                }
            }
        }).start();

        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                synchronized (lock){
                    while (flag%3!=2) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print("c");
                    flag++;
                    lock.notifyAll();
                }
            }
        }).start();
    }
}
